#define _CRT_SECURE_NO_WARNINGS 1
#include"Heap.h"
void CreateNDate()
{
	// 造数据
	int n = 10000;
	srand(time(0));
	const char* file = "data.txt";
	//打开一个文件
	FILE* fin = fopen(file, "w");
	//打开是否成功的检测
	if (fin == NULL)
	{
		perror("fopen error");
		return;
	}
	//生成1万个随机数
	for (int i = 0; i < n; ++i)
	{
		int x = rand() % 1000000;
		fprintf(fin, "%d\n", x);
	}
	//关闭文件
	fclose(fin);
}
void PrintTopK(char* failname, int k)
{
	//打开文件
	FILE* fout = fopen("data.txt", "r");
	//打开是否成功的检测
	if (fout == NULL)
	{
		perror("fopen error");
		return;
	}


	//创建一个10个整形的数组
	int* minheap = (int*)malloc(sizeof(int) * k);
	//检测开辟是否成功
	if (minheap == NULL)
	{
		perror("malloc fail");
		return;
	}


	//从文件里取出十个数据，放进数组里
	for (int i = 0; i < k; i++)
	{
		fscanf(fout, "%d", &minheap[i]);
	}

	//对数组进行向下调整建立小堆
	for (int i = (k - 2) / 2; i >= 0; i--)
	{
		AdjustDown(minheap, k, i);
	}
	//再依次读取文件中，剩下的数，比堆顶大，则替换堆顶，然后进行向下调整
	int x = 0;
	while (fscanf(fout, "%d", &x) != EOF)
	{
		if (x > minheap[0])
		{
			minheap[0] = x;
			AdjustDown(minheap, k, 0);
		}
	}

	//打印这最大的10个数字
	for (int i = 0; i < k; i++)
	{
		printf("%d ", minheap[i]);
	}

	//释放
	free(minheap);
	//关闭文件
	fclose(fout);
}
int main()
{

	//CreateNDate();
	PrintTopK("data.txt", 10);
}
